package hjw.com.controller.adm;

import hjw.com.entity.Type;
import hjw.com.service.TypeServiceImpl;
import hjw.com.util.PackJsn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Project:Academic - AdmTypeController
 *
 * @author IvanWei玮 -- maste
 * @version 1.0
 * @DataTime 2025/2/20 14:24
 * @since 1.8
 */
@RestController
@RequestMapping("api/adm/type")
public class AdmTypeController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final TypeServiceImpl typeDao;

    @Autowired
    public AdmTypeController(TypeServiceImpl typeDao) {
        this.typeDao = typeDao;
    }

    @GetMapping("/findAll")
    public String findAll() {
        logger.info("findAllByType");
        List<Type> type = typeDao.findAllByType();
        if (type.isEmpty()) {
            return PackJsn.pack(203, "商品主要类型信息为空", null);
        }
        logger.info("findAllByCategory");
        List<Type> category = typeDao.findAllByCategory();
        Map<String, Object> map = new HashMap<>(2);
        map.put("type", type);
        map.put("category", category);
        return PackJsn.pack(200, "商品类型信息", map);
    }

    @GetMapping("/findById/{id}")
    public String findById(@PathVariable("id") Integer id) {
        logger.info("findById");
        if(id == null){
            return PackJsn.pack(203, "商品类型id为空", null);
        }
        Type type = typeDao.findOneById(id);
        if(type == null){
            return PackJsn.pack(203, "商品类型信息为空", null);
        }
        return PackJsn.pack(200,"类型信息",type);
    }

    @PostMapping("/update")
    public String update(@RequestParam Map<String, Object> map){
        if (map.get("id") == null || map.get("id").toString().isEmpty()){
            return PackJsn.pack(203,"无编号修改，数据异常");
        }
        if (Integer.parseInt(map.get("id").toString()) == 0){
            int add = typeDao.add(map);
            if(add != 0){
                return PackJsn.pack(200, "添加成功");
            }
            return PackJsn.pack(200, "数据异常，添加失败");

        }
        int i = typeDao.updateById(map);

        if ( i != 0){
            return PackJsn.pack(200, "更新成功");
        }

        return PackJsn.pack(203, "数据异常，更新失败");
    }

    @GetMapping("/delete/{id}")
    public String del(@PathVariable("id") Integer id) {
        logger.info("del=" + id);
        if (id == null || id == 0) {
            return PackJsn.pack(203, "删除失败");
        }
        int i = typeDao.delete(id);
        if (i == 0) {
            return PackJsn.pack(203, "删除失败");
        }
        return PackJsn.pack(200, "删除成功");
    }
}
